package com.example.aichat.controller;


import com.example.aichat.mapper.UserMapper;
import com.example.aichat.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "http://localhost:8081")
@RequestMapping("/user")
public class loginController {

    private final UserMapper userMapper;

    @Autowired
    public loginController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @PostMapping("/login")
    public String login(@RequestBody User user) {
        System.out.println(user.getUser_account()+" "+user.getUser_psw());
        User user2 = userMapper.login(user.getUser_account(), user.getUser_psw());
        if (user2 != null) {
            return "登录成功";
        } else {
            return "用户名或密码错误";
        }
    }

    @PostMapping("/register")
    public String register(@RequestBody User user) {

        // 使用新的 findByAccount 方法判断用户名是否存在
        System.out.println(user.getUser_account()+" "+user.getUser_psw());

        User existingUser = userMapper.findByAccount(user.getUser_account());
        if (existingUser != null) {
            return "用户名已存在";
        }

        // 注册新用户
        User newUser = new User();
        newUser.setUser_account(user.getUser_account());
        newUser.setUser_psw(user.getUser_psw());
        int result = userMapper.insertUser(newUser);

        return result > 0 ? "注册成功" : "注册失败";
    }


}
